const mysql = require ("./../oper_sql/sqls.js")

var express = require('express');
var router = express.Router();

//response 格式化返回
var res_call= function(data){
    var code= data ? 1 : 0;
    return { body: data, code: code};
};
// 封装 get/post参数获取
var getParams= function(req){
    //注---> 优先级： params> body> query
    return Object.assign(req.query, req.body, req.params);
};

/* 查询单条记录 */
router.get('/login', function(req, res, next) {
    var reqData= getParams(req);
    mysql.findOne("test_user", {name: reqData.name, pass: reqData.pass}, function(data){
      res.json(Object.assign( {msg: data ? '登录成功' : '登录失败'}, res_call(data) ));
    });
});
/* 写入数据 */
router.post('/add', function(req, res, next) {
    var reqData= getParams(req);
    mysql.insert("test_user", {name: reqData.name, pass: reqData.pass}, function(data){
        res.json(Object.assign( {msg: data ? '注册成功' : '注册失败'}, res_call(data), {body: {}}));
    });
});

/* 查询所有 */
router.use('/select/all', function(req, res, next) {
    mysql.select("test_user", "", function(data){
        res.json(Object.assign( {msg: data ? '获取成功' : '获取失败'}, res_call(data) ));
    });
});

/* 更新 */
router.use('/update', function(req, res, next) {
    var reqData= getParams(req);
    mysql.update("test_user", {name: reqData.name, pass: reqData.pass}, {id: reqData.id}, function(data){
        res.json(Object.assign( {msg: data ? '更新成功' : '更新失败'}, res_call(data), {body: {}}));
    });
});

/* 删除 */
router.use('/del', function(req, res, next) {
    var reqData= getParams(req);
    mysql.del("test_user", {id: reqData.id}, function(data){
        res.json(Object.assign( {msg: data ? '删除成功' : '删除失败'}, res_call(data), {body: {}}));
    });
});

module.exports = router;
